/*
 * @lc app=leetcode.cn id=107 lang=cpp
 *
 * [107] 二叉树的层序遍历 II
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<int> layer;                      // 当前层的节点值
        vector<vector<int>> result;             // 整棵树的节点值
        if (root == nullptr) {
            return result;
        }

        queue<TreeNode*> nodeQueue;             // 待访问的节点队列 

        nodeQueue.push(root);
        while (!nodeQueue.empty()) {
            int length = nodeQueue.size();      // 获取该层的节点数量
            for (int i = 0; i < length; i++) {
                // 取出队列头部节点
                TreeNode* node = nodeQueue.front();
                nodeQueue.pop();
                layer.push_back(node->val);
                
                // 将子节点插入队列尾部
                if (node->left != nullptr) {
                    nodeQueue.push(node->left);
                }
                if (node->right != nullptr) {
                    nodeQueue.push(node->right);
                }
            }
            // 将该层的节点值保存至结果中
            result.push_back(layer);
            layer.clear();
        }
        
        // 翻转结果
        reverse(result.begin(), result.end());

        return result;
    }
};
// @lc code=end

